using System;
using System.Collections.Generic;
using Castle.DynamicProxy;
using CosyTrade.Core;

namespace CosyTrade.Network.WebServicesProxy
{
    [Addin("WebServicesPortalProxy")]
    public class WebServicesPortalFactory : AddinBase, IRemotingPortalFactory
    {
        private static readonly object LOCK_OBJECT = new object();
        private readonly Dictionary<Type, object> addinCache = new Dictionary<Type, object>();
        private readonly IMethodInvoke methodInvoke = new MethodInvoke();

        public T RegisterProxy<T>(string addinName)
        {
            if (!addinCache.ContainsKey(typeof(T)))
                lock (LOCK_OBJECT)
                    if (!addinCache.ContainsKey(typeof(T)))
                    {
                        ProxyInterceptor interceptor = new ProxyInterceptor(methodInvoke, addinName);
                        ProxyGenerator generator = new ProxyGenerator();
                        ProxyGenerationOptions options = new ProxyGenerationOptions();
                        options.BaseTypeForInterfaceProxy = typeof(RemotingObject);

                        addinCache.Add(typeof(T), generator.CreateInterfaceProxyWithoutTarget(typeof(T), interceptor));
                    }
            return (T)addinCache[typeof(T)];
        }

        public T GetProxy<T>()
        {
            return (T)addinCache[typeof(T)];
        }
    }

    public class MethodInvoke : IMethodInvoke
    {
        private readonly WebServicesPortal.Portal portal = new WebServicesPortal.Portal();
        public byte[] Invoke(byte[] requestData)
        {
            return portal.MethodInvoke(requestData);
        }
    }
}